package com.le.dub.service.impl;

 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.StreamInputTts;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsListener;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsResponse;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
 import com.le.dub.common.BusinessRuntimeException;
 import com.le.dub.common.cosyvoice.GuoleCosyVoiceB;
import com.le.dub.common.cosyvoice.GuoleCosyVoiceDemo;
import com.le.dub.service.IAliYunService;
import com.le.dub.service.IVoiceService;
import com.le.dub.service.IFileService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.ByteBuffer;

/**
 * 阿里音色服务实现
 *
 * @author guole
 * @created 2024/10/5
 */
@ConditionalOnProperty(name = "voiceService", havingValue = "ali")
@Service
@Slf4j
public class AliCosyVoiceServiceImpl implements IVoiceService {
    @Resource
    private IAliYunService aliYunService;
    @Value("${aliyun.appKey}")
    private String appKey;


    private NlsClient nlsClient=null;
    private IAcsClient iAcsClient=null;


    @Override
    public byte[] textToSpeech(String text, String cosyVoiceName) {
        StreamInputTts synthesizer = null;
        GuoleCosyVoiceB b = new GuoleCosyVoiceB();
        byte[] speechByte = null;
        try {


            synthesizer = new StreamInputTts(getNlsClient(), getSynthesizerListener(b));
            synthesizer.setAppKey(appKey);
            //设置返回音频的编码格式。
            synthesizer.setFormat(OutputFormatEnum.MP3);
            //设置返回音频的采样率。
            synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_24K);
            synthesizer.setVoice(cosyVoiceName);
            //音量，范围是0~100，可选，默认50。
            synthesizer.setVolume(50);
            //语调，范围是-500~500，可选，默认是0。
            synthesizer.setPitchRate(0);
            //语速，范围是-500~500，默认是0。
            synthesizer.setSpeechRate(0);
            //此方法将以上参数设置序列化为JSON发送给服务端，并等待服务端确认。
            long start = System.currentTimeMillis();
            synthesizer.startStreamInputTts();
            System.out.println("tts start latency " + (System.currentTimeMillis() - start) + " ms");

            //发送流式文本数据。
            synthesizer.sendStreamInputTts(text);
            //通知服务端流式文本数据发送完毕，阻塞等待服务端处理完成
            synthesizer.stopStreamInputTts();
            speechByte = b.getSpeechByte();

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessRuntimeException("500","阿里云语音生成异常");

        } finally {
            if (null != synthesizer) {
                synthesizer.close();
            }
        }


        return speechByte;
    }

    @Override
    public String cloneVoice(String voiceName, String fileUrl) throws Exception {

        CommonRequest cloneRequest = buildRequest("CosyVoiceClone");
        cloneRequest.putBodyParameter("VoicePrefix", voiceName);
        cloneRequest.putBodyParameter("Url", fileUrl);
        // 设定等待超时时间为60s
        cloneRequest.setSysReadTimeout(60000);
        String response = sendRequest(cloneRequest);
        JSONObject responseJson= JSON.parseObject(response);
        if(responseJson.getString("Code").equals("20000000")){
            return responseJson.getString("VoiceName");
        }
        log.info("cloneVoice-response---"+response);

        return null;
    }

    private StreamInputTtsListener getSynthesizerListener(GuoleCosyVoiceB b) {
        StreamInputTtsListener listener = null;
        try {
            listener = new StreamInputTtsListener() {


                private boolean firstRecvBinary = true;

                //流式文本语音合成开始
                @Override
                public void onSynthesisStart(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus());
                }

                //服务端检测到了一句话的开始
                @Override
                public void onSentenceBegin(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus());
                    System.out.println("Sentence Begin");
                }

                //服务端检测到了一句话的结束，获得这句话的起止位置和所有时间戳
                @Override
                public void onSentenceEnd(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus() + ", subtitles: " + response.getObject("subtitles"));

                }

                //流式文本语音合成结束
                @Override
                public void onSynthesisComplete(StreamInputTtsResponse response) {
                    // 调用onSynthesisComplete时，表示所有TTS数据已经接收完成，所有文本都已经合成音频并返回。
                    System.out.println("name: " + response.getName() + ", status: " + response.getStatus());
                    //  audioPlayer.stop();
                }

                //收到语音合成的语音二进制数据
                @Override
                public void onAudioData(ByteBuffer message) {
                    b.addByte(message);
                }

                //收到语音合成的增量音频时间戳
                @Override
                public void onSentenceSynthesis(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus() + ", subtitles: " + response.getObject("subtitles"));
                }

                @Override
                public void onFail(StreamInputTtsResponse response) {
                    // task_id是调用方和服务端通信的唯一标识，当遇到问题时，需要提供此task_id以便排查。
                    System.out.println(
                            "session_id: " + getStreamInputTts().getCurrentSessionId() +
                                    ", task_id: " + response.getTaskId() +
                                    //状态码
                                    ", status: " + response.getStatus() +
                                    //错误信息
                                    ", status_text: " + response.getStatusText());
                    // audioPlayer.stop();
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listener;
    }

    private   CommonRequest buildRequest(String popApiName) {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("nls-slp.cn-shanghai.aliyuncs.com");
        request.setVersion("2019-08-19");
        request.setAction(popApiName);
        request.setProtocol(ProtocolType.HTTPS);
        return request;
    }
    private  String sendRequest(CommonRequest request) {
        try {
            CommonResponse response = getIAcsClient().getCommonResponse(request);
            return response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
    private NlsClient   getNlsClient() {
        if(nlsClient==null){
            String token = aliYunService.getAccessToken();
            String url = "wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1";

            nlsClient = new NlsClient(url, token);
        }

        return nlsClient;
    }
    private IAcsClient getIAcsClient(){
        if(iAcsClient==null){
            // 创建DefaultAcsClient实例并初始化
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai","LTAI5t6rV2sRnzL5p1WpAQse"
                    ,
                    "lqns8N8N7C4FqGYniJbC5ERHrIM0hx");
            iAcsClient = new DefaultAcsClient(profile);
        }
        return iAcsClient;

    }
}
